<template>
    <el-dialog
        v-model="dialogVisible"
        :title="type === 'add' ? '新增权限' : '编辑权限'"
        width="500px"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="permissionForm"
            :rules="rules"
            label-width="100px"
        >
            <el-form-item label="权限名称" prop="permissionName">
                <el-input v-model="permissionForm.permissionName" placeholder="请输入权限名称" />
            </el-form-item>
            <el-form-item label="权限编码" prop="code">
                <el-input v-model="permissionForm.code" placeholder="请输入权限编码" />
            </el-form-item>
            <el-form-item label="排序" prop="permissionSlot">
                <el-input-number 
                    v-model="permissionForm.permissionSlot" 
                    :min="1" 
                    :max="999"
                    placeholder="请输入排序值，数字越小越靠前" 
                    style="width: 100%" 
                />
            </el-form-item>
            <el-form-item label="父级权限" prop="parentUUID">
                <el-select v-model="permissionForm.parentUUID" placeholder="请选择父级权限" style="width: 100%">
                    <el-option label="无" value="" />
                    <el-option
                        v-for="item in parentOptions"
                        :key="item.uUID"
                        :label="item.permissionName"
                        :value="item.uUID"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Create, Update, type UserPermission } from '@/apis/permission'

const props = defineProps<{
    modelValue: boolean
    type: 'add' | 'edit'
    permissionData?: UserPermission
    permissionList: UserPermission[]
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
}>()

// 状态变量
const dialogVisible = ref(props.modelValue)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const permissionForm = ref<UserPermission>({
    permissionName: '',
    code: '',
    permissionSlot: 1,
    parentUUID: '',
    updateTime: '',
    uUID: ''
})

// 父级权限选项（排除自己）
const parentOptions = computed(() => {
    return props.permissionList.filter(item => item.uUID !== permissionForm.value.uUID)
})

// 表单校验规则
const rules = {
    permissionName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入权限编码', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    permissionSlot: [
        { required: true, message: '请输入排序值', trigger: 'blur' },
        { type: 'number', message: '排序值必须为数字', trigger: 'blur' }
    ]
}

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
    emit('update:modelValue', val)
})

// 监听编辑数据
watch(() => props.permissionData, (val) => {
    if (val) {
        permissionForm.value = { ...val }
    } else {
        permissionForm.value = {
            permissionName: '',
            code: '',
            permissionSlot: 1,
            parentUUID: '',
            updateTime: '',
            uUID: ''
        }
    }
}, { immediate: true })

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid, fields) => {
        if (!valid) return
        
        submitLoading.value = true
        try {
            if (props.type === 'add') {
                await Create(permissionForm.value)
                ElMessage.success('新增成功')
            } else {
                await Update(permissionForm.value)
                ElMessage.success('更新成功')
            }
            handleClose()
            emit('success')
        } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        } finally {
            submitLoading.value = false
        }
    })
}

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false
    formRef.value?.resetFields()
    permissionForm.value = {
        permissionName: '',
        code: '',
        permissionSlot: 1,
        parentUUID: '',
        updateTime: '',
        uUID: ''
    }
}
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}
</style> 